<template>
  <div class="searchArea">
    <form action="###" class="searchForm">
      <input
        type="text"
        id="autocomplete"
        class="input-error input-xxlarge"
        v-model="keyword"
        placeholder="请输入商品名称"
        @keyup.enter="goSearch"
      />
      <button
        class="sui-btn btn-xlarge btn-danger"
        type="button"
        @click="goSearch"
      >
        搜 索
      </button>
    </form>
  </div>
</template>

<script>
export default {
  name: "HeaderSearch",
  data() {
    return {
      keyword: "",
    };
  },
  methods: {
    //搜索按钮页面跳转并传参数
    goSearch() {
      //this.$router.push(`/search/${this.keyword}`);
      const query = this.$route.query; //获取query参数
      //跳转配置
      const location = {
        name: "Search",
        params: { keyword: this.keyword || "undefined" },
      };
      //判断是否有query参数 有就添加到location中与params 合并
      if (query) {
        location.query = query;
      }
      this.$router.push(location);
    },
  },
  mounted() {
    //通过【搜索页 面包屑】的全局数据总线：接受delKeyword事件 清空搜索框中的关键字数据
    this.$eventBus.$on("delKeyword", () => {
      this.keyword = "";
    });
  },
  beforeDestroy() {
    this.$eventBus.$off("delKeyword"); //组件销毁前关闭delKeyword全局数据总线
  },
};
</script>

<style scoped lang="less">
.searchArea {
  float: right;
  margin-top: 35px;

  .searchForm {
    overflow: hidden;

    input {
      box-sizing: border-box;
      width: 490px;
      height: 40px;
      padding: 0px 15px;
      border: 2px solid #3498db;
      float: left;

      &:focus {
        outline: none;
      }
    }

    button {
      height: 40px;
      width: 68px;
      background-color: #3498db;
      border: none;
      color: #fff;
      float: left;
      cursor: pointer;
      font-size: 16px;
      &:focus {
        outline: none;
      }
    }
  }
}
</style>